import React, { useReducer } from 'react';


const useForm = (initialFields) => {
    const formReducer = (state, action) => {
        console.log('reducer执行', action);
        const { type } = action;
        switch (type) {
            case 'set': {
                return {
                    ...state,
                    ...action,
                };
            }
            case 'reset': {
                return initialFields;
            }
            default:
                break;
        }
        return state;
    };

    const [values, dispatch] = useReducer(formReducer, initialFields);

    const getFieldsProps = key => {
        //给input做属性用
        return {
            value: values[key], // values[key] ? values.user
            onChange: event => 
                dispatch({type: 'set', values: { [key]: event.target.value } }),
        };
    };

    const setFieldsValue = values => {
        dispatch({type: 'set', values});
    };

    const resetFields = () => {
        dispatch({type: 'reset'});
    };

    return {values, getFieldsProps, setFieldsValue, resetFields};
};


function UseFormInput() {
    const { getFieldsProps, setFieldsValue } = useForm({
        user: '',
        pwd: '',
    });

    return (
        <div>
            <input type="text" placeholder="用户名" {...getFieldsProps('user')} />
            <input type="password" placeholder="密码" {...getFieldsProps('pwd')} />
            <button
                onClick={() => setFieldsValue({user: 'Mike', pwd: '88888888'})}
            >
                设置密码
            </button>
            <button>提交</button>
        </div>
    );
}


export default UseFormInput;